<template>
  <div class="view">
    <div style="padding: 20px">
      <el-input placeholder="请输入航空名称" style="width: 15%; margin-right:15px" v-model="selectForm.airlineName"
        clearable></el-input>

      <el-input placeholder="请输入起飞城市" style="width: 15%; margin-right:15px" v-model="selectForm.departureCity"
        clearable></el-input>

      <el-input placeholder="请输入抵达城市" style="width: 15%; margin-right:15px" v-model="selectForm.arrivalCity"
        clearable></el-input>

      <el-button type="primary" @click="pageQuery" style="margin-left: 20px;">查询</el-button>
      <el-button type="text" @click="cleanSelectI" style="margin-left: 20px;">清空</el-button>
      <el-button type="primary" style="float: right;" @click="openAddG()">+ 添加航班信息</el-button>
    </div>

    <el-table :data="records" stripe style="width: 100%; margin-top:20px">
      <!-- <el-table-column prop="id" label="序号" width="100"></el-table-column> -->
      <el-table-column prop="airlineName" label="航空名称" width="230"></el-table-column>
      <el-table-column prop="departureCity" label="起飞机场" width="160"></el-table-column>
      <el-table-column prop="arrivalCity" label="到达机场" width="160"></el-table-column>
      <el-table-column prop="departureTime" label="起飞时间" width="160"></el-table-column>
      <el-table-column prop="arrivalTime" label="到达时间" width="160"></el-table-column>
      <el-table-column prop="price" label="机票费用(每人)" width="120">
        <template #default="scope">
          <del>¥{{ scope.row.price }}</del>
          {{ scope.row.salePrice}} 元
        </template>
      </el-table-column>
      <!-- <el-table-column prop="discount" label="折扣价" width="80">
        <template slot-scope="scope">
          {{ (scope.row.discount * 10).toFixed(1) }}折
        </template>
      </el-table-column> -->
      <el-table-column prop="seatAvailable" label="空闲/总座" width="120">
        <template slot-scope="scope">
          {{ scope.row.seatAvailable }}/{{ scope.row.seatTotal }}
        </template>
      </el-table-column>

      <el-table-column prop="status" label="操作" width="160">
        <template slot-scope="scope">
          <el-button type="text" @click="edit(scope.row)">编辑</el-button>
          <!-- <el-button type="text" @click="updataStatus(scope.row)">
            <span v-if="scope.row.status === 0">
              启售
            </span>
            <span v-if="scope.row.status === 1" style="color: #f56c6c;">
              停售
            </span>
          </el-button> -->
          <el-button type="text" @click="drop(scope.row)" style="color: #f56c6c;">删除</el-button>
          <el-button type="text" @click="openAddO(scope.row)" >下单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top: 20px; text-align:center;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
        :page-sizes="[6, 10, 14, 18]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 修改航班信息 -->
    <el-dialog title="修改航班信息" :visible.sync="editFormVisible">
      <el-form :model="form" class="update">
        <el-form-item label="航空名称" :label-width="formLabelWidth">
          
          <el-input v-model="form.airlineName" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="起飞城市" :label-width="formLabelWidth">
          
          <el-input v-model="form.departureCity" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="抵达城市" :label-width="formLabelWidth">
          
          <el-input v-model="form.arrivalCity" autocomplete="off" clearable></el-input>
        </el-form-item>

        <el-form-item label="起飞时间" :label-width="formLabelWidth">
          <el-date-picker v-model="form.departureTime" type="datetime" placeholder="选择起飞时间" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
        </el-form-item>

        <el-form-item label="抵达时间" :label-width="formLabelWidth">
          <el-date-picker v-model="form.arrivalTime" type="datetime" placeholder="选择抵达时间" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
        </el-form-item>

        <el-form-item label="航班原价(元)" :label-width="formLabelWidth">
          
          <el-input v-model="form.price" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="票价折扣" :label-width="formLabelWidth">
          
          <el-input v-model="form.discount" autocomplete="off" clearable>
            <template slot="append">折</template>
          </el-input>
        </el-form-item>
        <el-form-item label="总座位数" :label-width="formLabelWidth">
          
          <el-input v-model="form.seatTotal" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="可用座位数" :label-width="formLabelWidth">
          
          <el-input v-model="form.seatAvailable" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="updateInfo()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加航班 -->
    <el-dialog title="飞机票表" :visible.sync="addFormVisible">
      <el-form :model="form" class="update">
        <el-form-item label="航空名称" :label-width="formLabelWidth">
          
          <el-input v-model="form.airlineName" placeholder="航空名称" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="出发机场" :label-width="formLabelWidth">
          
          <el-input v-model="form.departureCity" placeholder="出发机场" autocomplete="off" clearable></el-input>
        </el-form-item>
        
        <el-form-item label="到达机场" :label-width="formLabelWidth">
          
          <el-input v-model="form.arrivalCity" placeholder="到达机场" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="出发时间" :label-width="formLabelWidth">
          <el-date-picker v-model="form.departureTime" type="datetime" placeholder="选择时间" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
        </el-form-item>
        <el-form-item label="到达时间" :label-width="formLabelWidth">
          <el-date-picker v-model="form.arrivalTime" type="datetime" placeholder="选择时间" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
        </el-form-item>
        <el-form-item label="机票费用" :label-width="formLabelWidth">
          <el-input v-model="form.price" placeholder="机票费用" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="折扣" :label-width="formLabelWidth">
          <el-input v-model="form.discount" placeholder="折扣" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="总票数" :label-width="formLabelWidth">
          
          <el-input v-model="form.seatTotal" placeholder="总票数" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="剩余票数" :label-width="formLabelWidth">
          <el-input v-model="form.seatAvailable" placeholder="剩余票数" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false;resetForm()">取 消</el-button>
        <el-button type="primary" @click="addFlight()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加订单 -->
     <el-dialog title="下单" :visible.sync="addOrderVisible">
      <el-form :model="userForm" class="update">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="userForm.userName" placeholder="姓名" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input v-model="userForm.userPhone" placeholder="手机号" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="身份证号" :label-width="formLabelWidth">
          <el-input v-model="userForm.userID" placeholder="身份证号" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false;resetForm()">取 消</el-button>
        <el-button type="primary" @click="addFOrder()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      name: '',
      page: 1,
      pageSize: 6,
      total: 0,
      records: [],
      CatInfo:[],
      editFormVisible: false,
      addFormVisible: false,
      addOrderVisible: false,
      flightId: '',
      flightP:'',
      formLabelWidth: '120px',
      form: {
        id: '',
        airlineName: '',
        departureCity: '',
        arrivalCity: '',
        departureTime: '',
        arrivalTime: '',
        price: '',
        discount: '',
        salePrice:'',
        seatTotal: '',
        seatAvailable: ''
      },
      selectForm: {
        airlineName: '',
        departureCity: '',
        arrivalCity: ''
      },
      userForm: {
        userName: '',
        userPhone: '',
        userID:''
      }
    }
  },
  created() {
    this.pageQuery();
  },
  methods: {
    cleanSelectI() {
      this.selectForm.airlineName = '';
      this.selectForm.departureCity = '';
      this.selectForm.arrivalCity = '';
      this.pageQuery(true)
    },
    openAddG() {
      this.addFormVisible = true;
      this.getCategory();
    },
    openAddO(row) {
      this.flightId = row.id,
      this.flightP = row.salePrice,
      this.addOrderVisible = true;
    },
    addFOrder() {
      axios({
        url: '/api/order',
        method: 'put',
        params: {
          id: this.flightId,
          price: this.flightP,
          userName: this.userForm.userName,
          userPhone: this.userForm.userPhone,
          userID: this.userForm.userID
        },
        headers: {
          token: this.$store.state.user.token
        }
      }).then(res => {
        if (res.data.code === 1) {
          this.$message.success("添加订单成功！");
          this.addOrderVisible = false;
          // this.pageQuery();
          this.flightId = '',
          this.flightP=''
          // this.resetForm('form')
          this.pageQuery();
        }
        else {
          this.$message.error(res.data.msg)
        }
      }).catch(err => {
        this.handleError(err)
      })
    },
    // getCategory() {
    //   axios({
    //     url: '/api/category/list',
    //     headers: {
    //       token:this.$store.state.user.token
    //     }
    //   }).then(res => {
    //     this.CatInfo = res.data.data
    //   }).catch(err => {
    //     console.log(err);

    //   })
    // },
    drop(row) {
      this.$confirm('是否删除该航班信息?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios({
          url: '/api/flight',
          method: 'delete',
          params: {
            id: row.id
          },
          headers: {
            token: this.$store.state.user.token
          }
        }).then(res => {
          if (res.data.code === 1) {
            this.$message.success("删除成功！")
            this.pageQuery()
          }
          else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    edit(row) {
      this.form = row
      // this.getCategory()
      this.editFormVisible = true
    },
    updateInfo() {
      this.$confirm('是否修改航班信息?', '提示', {
        confirmButtonText: '确认修改',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios({
          url: '/api/flight',
          method: 'put',
          data: this.form,
          headers: {
            token: this.$store.state.user.token
          }
        }).then(res => {
          if (res.data.code === 1) {
            this.$message.success("修改成功！")
            this.pageQuery()
          }
          else {
            this.$message.error(res.data.msg)
          }
        })
        this.resetForm()
        this.pageQuery()
        this.editFormVisible = false;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    getById(row) {
      this.form.name = row.name;
      this.form.id = row.id;
    },
    addFlight() {
      axios({
        url: '/api/flight',
        method: 'post',
        data: this.form,
        headers: {
          token: this.$store.state.user.token
        }
      }).then(res => {
        if (res.data.code === 1) {
          this.$message.success("添加航班成功！");
          this.addFormVisible = false;
          this.pageQuery();
          this.resetForm('form')
        }
        else {
          this.$message.error(res.data.msg)
        }
      }).catch(err => {
        this.handleError(err)
      })
    },

    handleError(err) {
      console.error('An error occurred:', err);
      if (err.response) {
        if (err.response.status === 401) {
          this.$message.error("您的登录已过期，请重新登录");
          this.$router.push('/login')
        } else if (err.response.status === 500) {
          this.$message.error("服务器异常，请稍后再试");
          this.$router.push('/404')
        } else {
          this.$message.error("请求失败");
        }
      } else if (err.request) {
        this.$message.error("网络错误，请检查您的网络连接");
      } else {
        this.$message.error("请求异常！请稍后再试~");
      }
    },
    pageQuery(resetPage=false) {
      if (resetPage) {
        this.page = 1; // 每次查询时将页码重置为第一页
      }
      axios({
        url: '/api/flight/page',
        method: 'get',
        params: {
          airlineName: this.selectForm.airlineName,
          departureCity: this.selectForm.departureCity,
          arrivalCity: this.selectForm.arrivalCity,
          page: this.page,
          pageSize: this.pageSize
        },
        headers: {
          token: this.$store.state.user.token
        }
      }).then(res => {
        if (res.data.code === 1) {
          console.log("请求成功");
          this.total = res.data.data.total,
          this.records = res.data.data.records
        }
        else if (res.data.code === 0) {
          this.$message.error('请求失败,请稍后再试')
        }
      }).catch(err => {
        this.handleError(err)
      })
    },
    // 页码发生变化时发送请求
    handleCurrentChange(page) {
      this.page = page
      this.pageQuery()
    },
    // 每页数量发生变化发送请求
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageQuery()
    },
    updataStatus(row) {
      this.$confirm('是否修改商品状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const p = {
          id: row.id,
          status: !row.status ? 1 : 0
        }
        axios({
          url: `/api/goods/status/${p.status}`,
          method: 'post',
          params: {
            id: p.id
          },
          headers: {
            token: this.$store.state.user.token
          }
        }).then(res => {
          if (res.data.code === 1) {
            this.$message.success("修改成功！"),
              this.pageQuery()
          }
        }).catch(err => {
          this.$message.error('修改失败！')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    resetForm() {
      this.form.id = '';
      this.form.airlineName = '';
      this.form.departureCity = '';
      
      this.form.arrivalCity = '';
      
      this.form.departureTime = '';
      this.form.arrivalTime = '';
      this.form.price = '';
      
      this.form.discount = '';
      this.form.seatTotal = '';
      this.form.seatAvailable = '';
    }
  }
}
</script>

<style scoped>
.el-input {
  width: 40%;
}
.el-icon-success {
  color: #1dc779;
}

.el-icon-error {
  color: #f56c6c;
}
.view {
  width: 96%;
  margin: 1% auto;
  border-radius: 10px;
  background-color: #ffffff;
  padding: 10px;
  overflow: hidden;
}
</style>
